package com.mashiro.common.aop;

import com.mashiro.common.core.domain.AjaxResult;
import com.mashiro.common.core.page.TableDataInfo;
import com.mashiro.common.json.JsonUtil;
import com.mashiro.common.utils.secret.AesUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * 加解密注解切面类
 *
 *
 * @author mashiro
 */
@Aspect
@Component
public class SecretAop {

    /**
     * 定义切点
     */
    @Pointcut("execution(* com.mashiro..controller..*(..))")
    public void pointcut() {
    }

    @Value("${mashiro.aes.enable:false}")
    private boolean secretFlag;

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object responseObj = point.proceed();
        // 备份，防止加密失败，仍有原返回值可供返回
        AjaxResult ajaxResultBak = null;
        TableDataInfo tableDataInfoBak = null;
        if (secretFlag){
            try {
                if (responseObj instanceof AjaxResult) {
                    AjaxResult ajaxResult = (AjaxResult) responseObj;
                    ajaxResultBak = (AjaxResult)ajaxResult.clone();
                    Object responseData = ajaxResult.get(AjaxResult.DATA_TAG);
                    String json = JsonUtil.toJson(responseData);
                    String encrypt = AesUtil.encrypt(json);
                    ajaxResult.put(AjaxResult.DATA_TAG, encrypt);
                    ajaxResult.put(AjaxResult.SECRET_TAG, 1);
                } else if (responseObj instanceof TableDataInfo) {
                    ArrayList<String> arrayList = new ArrayList<>();
                    TableDataInfo tableDataInfo = (TableDataInfo) responseObj;
                    tableDataInfoBak = (TableDataInfo)tableDataInfo.clone();
                    List<?> responseRows = tableDataInfo.getRows();
                    for (Object row : responseRows) {
                        String json = JsonUtil.toJson(row);
                        String encrypt = AesUtil.encrypt(json);
                        arrayList.add(encrypt);
                    }
                    tableDataInfo.setRows(arrayList);
                    tableDataInfo.setSecret(1);
                }
            } catch (Exception ex) {
                if (responseObj instanceof AjaxResult) {
                    responseObj = ajaxResultBak;
                } else if (responseObj instanceof TableDataInfo) {
                    responseObj = tableDataInfoBak;
                }
            }
        }
        return responseObj;
    }

}
